package com.ffcs.web.controllers;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.ffcs.web.model.dto.BaseResponse;
import com.ffcs.web.model.dto.PeiPingjiasponse;
import com.ffcs.web.model.dto.Pingjia;
import com.ffcs.web.model.dto.StudyDescResponse;
import com.ffcs.web.model.dto.StudyResponse;
import com.ffcs.web.model.entity.Counselor;
import com.ffcs.web.model.entity.Study;
import com.ffcs.web.model.entity.WxUser;
import com.ffcs.web.model.requests.StudyRequest;
import com.ffcs.web.services.CollectNewsService;
import com.ffcs.web.services.CounselorService;
import com.ffcs.web.services.OrderService;
import com.ffcs.web.services.StudyService;
import com.ffcs.web.services.WxUserService;
import com.ffcs.web.utils.CommonConfig;

@Controller
public class StudyController {

	@Autowired
	private StudyService studyService;
	@Autowired
	private CounselorService counselorService;
	@Autowired
	private CollectNewsService collectNewsService;
	@Autowired
	private WxUserService wxUserService;
	@Autowired
	private OrderService orderService;
	
	private static String PIC_ADRESS=CommonConfig.getProperty("PIC_ADRESS");

	private Logger logger = Logger.getLogger(StudyController.class);
	
	/**
	 * 集训/培训详情
	 * @param id
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("gotoPeixunDesc")
	public void gotoPeixunDesc(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		String id=request.getParameter("studyId");
		Assert.notNull(id);
		Study study=studyService.getStudyDesc(id);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		study.setStartStudyStr(sdf.format(study.getStartStudy()));
		study.setEndStudyStr(sdf.format(study.getEndStudy()));
		study.setStudyUrl(CommonConfig.getProperty("PIC_URL_FRONT")+study.getStudyUrl());
		study.setContentUrl(CommonConfig.getProperty("PIC_URL_FRONT")+study.getContentUrl());
		
		if(null!=study.getStudyDirection()){
			String gd="";
			if(study.getStudyDirection().contains("1")){
				gd="学业倦怠";
			}
			if(study.getStudyDirection().contains("2")){
				gd="亲子关系";
			}
			if(study.getStudyDirection().contains("3")){
				gd="教育理念";
			}
			if(study.getStudyDirection().contains("4")){
				gd="学习习惯,";
			}
			if(study.getStudyDirection().contains("5")){
				gd="人际关系";
			}
			if(study.getStudyDirection().contains("6")){
				gd="沉迷网络";
			}
			if(study.getStudyDirection().contains("7")){
				gd="情绪管理";
			}
			if(study.getStudyDirection().contains("8")){
				gd="自控能力";
			}
			study.setStudyDirection(gd);
		}
		request.setAttribute("study",study);
		if(study.getStudyLabel().length()>0){
			
			String label[]=study.getStudyLabel().split(",");
			List<String> labelList=new ArrayList<String>();
			for (String lab : label) {
				labelList.add(lab);
			}
			request.setAttribute("labelList",labelList);
		}
		
		Counselor counselor=counselorService.getCounselor(study.getCounseTel());
		counselor.setPersonHead(CommonConfig.getProperty("PIC_URL_FRONT")+counselor.getPersonHead());
		request.setAttribute("counselor",counselor);
		WxUser wxUser=(WxUser)request.getSession().getAttribute("wxUser");
		boolean b=collectNewsService.isShouchang(study.getId(),wxUser.getId(),(short)2);
		if(b){
			request.setAttribute("isShouChang","1");
		}else{
			request.setAttribute("isShouChang","0");
		}
		request.getRequestDispatcher("peixunxiangqing.jsp").forward(request, response);
	}
	
	@RequestMapping("getPeinxunDesc")
	@ResponseBody
	public StudyDescResponse getPeinxunDesc(String studyId){
		StudyDescResponse studyDescResponse=new StudyDescResponse();
		Study study=studyService.getStudyDesc(studyId);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		study.setStartStudyStr(sdf.format(study.getStartStudy()));
		study.setStudyUrl(CommonConfig.getProperty("PIC_URL_FRONT")+study.getStudyUrl());
		if(null!=study.getStudyDirection()){
			String gd="";
			if(study.getStudyDirection().contains("1")){
				gd="学业倦怠";
			}
			if(study.getStudyDirection().contains("2")){
				gd="亲子关系";
			}
			if(study.getStudyDirection().contains("3")){
				gd="教育理念";
			}
			if(study.getStudyDirection().contains("4")){
				gd="学习习惯,";
			}
			if(study.getStudyDirection().contains("5")){
				gd="人际关系";
			}
			if(study.getStudyDirection().contains("6")){
				gd="沉迷网络";
			}
			if(study.getStudyDirection().contains("7")){
				gd="情绪管理";
			}
			if(study.getStudyDirection().contains("8")){
				gd="自控能力";
			}
			study.setStudyDirection(gd);
		}
		study.setEndStudyStr(sdf.format(study.getEndStudy()));
		studyDescResponse.setStudy(study);
		return studyDescResponse;
	}
	
	/**
	 * 集训/培训详情
	 * @param id
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("gotoConfirm")
	public void gotoConfirm(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		String id=request.getParameter("id");
		
		WxUser wxUser=(WxUser) request.getSession().getAttribute("wxUser");
		wxUser=wxUserService.getUserByUserId(wxUser.getId());
		if(null==wxUser.getTelephone() || "".equals(wxUser.getTelephone())){
			response.sendRedirect("peixunBindjsp.jsp?studyId="+id);
			return ;
		}
		
		Study study=studyService.getStudyDesc(id);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		study.setStartStudyStr(sdf.format(study.getStartStudy()));
		request.setAttribute("study",study);
		request.getRequestDispatcher("confirmPei.jsp").forward(request, response);
	}
	
	@RequestMapping("gotoConfirmBid")
	public void gotoConfirmBid(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		String id=request.getParameter("studyId");
		String telphone=request.getParameter("telphone");
		WxUser wxUser=(WxUser) request.getSession().getAttribute("wxUser");
		wxUserService.bindUser(wxUser, telphone);
		wxUser=wxUserService.getUserByUserId(wxUser.getId());
		request.getSession().setAttribute("wxUser",wxUser);
		Study study=studyService.getStudyDesc(id);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		study.setStartStudyStr(sdf.format(study.getStartStudy()));
		request.setAttribute("study",study);
		request.getRequestDispatcher("confirmPei.jsp").forward(request, response);
	}
	
	
	@RequestMapping("getPeiPingjia")
	@ResponseBody
	public PeiPingjiasponse getStudyList(String studyId){
		PeiPingjiasponse peiPingjiasponse=new PeiPingjiasponse();
		List<Pingjia> pingjiaList=orderService.getPeiPingjia(studyId);
		peiPingjiasponse.setResultCode("0");
		peiPingjiasponse.setResultDesc("success");
		peiPingjiasponse.setPingjiaList(pingjiaList);
		return peiPingjiasponse;
	}
	
	/**
	 * 集训/培训列表
	 * @param id
	 * @return
	 */
	@RequestMapping("deleteStudy")
	@ResponseBody
	public BaseResponse deleteStudy(HttpServletRequest request,StudyRequest studyRequest){
		BaseResponse baseesponse=new BaseResponse();
		String studyId=request.getParameter("studyId");
		try {
			studyService.deleteStudy(studyId);
		} catch (Exception e) {
			baseesponse.setResultCode("-1");
			baseesponse.setResultDesc("删除培训失败");
			return baseesponse;
		}
		
		baseesponse.setResultCode("0");
		baseesponse.setResultDesc("success");
		return baseesponse;
		
	}
	
	/**
	 * 判断是否已评价
	 * @param request
	 * @param studyRequest
	 * @param studyId
	 * @return
	 */
	@RequestMapping("isHuifuPeixun")
	@ResponseBody
	public BaseResponse isHuifuPeixun(HttpServletRequest request,StudyRequest studyRequest,String studyId){
		BaseResponse baseResponse=new BaseResponse();
		WxUser wxUser=(WxUser)request.getSession().getAttribute("wxUser");
		String flag=studyService.isHuifuPeixun(wxUser.getId(),studyId);
		if(flag.contains("0")){
			baseResponse.setResultCode("0");
			baseResponse.setResultDesc(flag.substring(2,flag.length()));
			return baseResponse;
		}else{
			baseResponse.setResultCode(flag);
			baseResponse.setResultDesc("success");
			return baseResponse;
		}
	}
	
	/**
	 * 集训/培训列表
	 * @param id
	 * @return
	 */
	@RequestMapping("getStudyList")
	@ResponseBody
	public StudyResponse getStudyList(HttpServletRequest request,StudyRequest studyRequest){
		StudyResponse studyResponse=new StudyResponse();
//		
//		if(null==studyRequest.getCityName() || "".equals(studyRequest.getCityName())){
//			if(null!=request.getSession().getAttribute("cityName") && !"".equals(request.getSession().getAttribute("cityName"))){
//				String cityName=(String) request.getSession().getAttribute("cityName");
//				studyRequest.setCityName(cityName.substring(0,2));
//			}
//		}
		
		List<Study> studyList=studyService.getStudyList(studyRequest);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		for (Study study : studyList) {
			if(null!=study.getStudyDirection()){
				String gd="";
				if(study.getStudyDirection().contains("1")){
					gd+="学业倦怠,";
				}
				if(study.getStudyDirection().contains("2")){
					gd+="亲子关系,";
				}
				if(study.getStudyDirection().contains("3")){
					gd+="教育理念,";
				}
				if(study.getStudyDirection().contains("4")){
					gd+="学习习惯,";
				}
				if(study.getStudyDirection().contains("5")){
					gd+="人际关系,";
				}
				if(study.getStudyDirection().contains("6")){
					gd+="沉迷网络,";
				}
				if(study.getStudyDirection().contains("7")){
					gd+="情绪管理,";
				}
				if(study.getStudyDirection().contains("8")){
					gd+="自控能力,";
				}
				gd=gd.substring(0, gd.length()-1);
				study.setStudyDirection(gd);
			}else{
				study.setStudyDirection("");
			}
			study.setStudyUrl(CommonConfig.getProperty("PIC_URL_FRONT")+study.getStudyUrl());
			study.setStartStudyStr(sdf.format(study.getStartStudy()));
			study.setEndStudyStr(sdf.format(study.getEndStudy()));
		}
		studyResponse.setResultCode("0");
		studyResponse.setResultDesc("success");
		studyResponse.setStudylist(studyList);
		return studyResponse;
	}
	
	/**
	 * 集训/培训列表
	 * @param id
	 * @return
	 */
	@RequestMapping("getMyStudyList")
	@ResponseBody
	public StudyResponse getMyStudyList(HttpServletRequest request,String studyType){
		StudyResponse studyResponse=new StudyResponse();
		
		//TODO判断session
		if(null==request.getSession().getAttribute("counseTel") || "".equals(request.getSession().getAttribute("counseTel"))){
			studyResponse.setResultCode("-1");
			studyResponse.setResultDesc("咨询师登录超时");
			return studyResponse;
		}
		String counseTel=(String)request.getSession().getAttribute("counseTel");
		
		List<Study> studyList=studyService.getStudyList(counseTel,studyType);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		for (Study study : studyList) {
			if(null!=study.getStudyDirection()){
				String gd="";
				if(study.getStudyDirection().contains("1")){
					gd+="学业倦怠,";
				}
				if(study.getStudyDirection().contains("2")){
					gd+="亲子关系,";
				}
				if(study.getStudyDirection().contains("3")){
					gd+="教育理念,";
				}
				if(study.getStudyDirection().contains("4")){
					gd+="学习习惯,";
				}
				if(study.getStudyDirection().contains("5")){
					gd+="人际关系,";
				}
				if(study.getStudyDirection().contains("6")){
					gd+="沉迷网络,";
				}
				if(study.getStudyDirection().contains("7")){
					gd+="情绪管理,";
				}
				if(study.getStudyDirection().contains("8")){
					gd+="自控能力,";
				}
				gd=gd.substring(0, gd.length()-1);
				study.setStudyDirection(gd);
			}else{
				study.setStudyDirection("");
			}
			study.setStudyUrl(CommonConfig.getProperty("PIC_URL_FRONT")+study.getStudyUrl());
			study.setStartStudyStr(sdf.format(study.getStartStudy()));
			study.setEndStudyStr(sdf.format(study.getEndStudy()));
		}
		studyResponse.setResultCode("0");
		studyResponse.setResultDesc("success");
		studyResponse.setStudylist(studyList);
		return studyResponse;
	}
	
	/**
	 * 修改培训/集训
	 * @param id
	 * @return
	 * @throws ParseException 
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("updatePeixun")
	public void updatePeixun(HttpServletRequest request,HttpServletResponse resp) throws ParseException, IOException, ServletException{
		String studyId=request.getParameter("studyId");
		Study study=studyService.getStudyDesc(studyId);
		study.setStudyUrl(CommonConfig.getProperty("PIC_URL_FRONT")+study.getStudyUrl());
		study.setContentUrl(CommonConfig.getProperty("PIC_URL_FRONT")+study.getContentUrl());
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		study.setStartStudyStr(sdf.format(study.getStartStudy()));
		study.setEndStudyStr(sdf.format(study.getEndStudy()));
		request.setAttribute("study",study);
		String labels[]=study.getStudyLabel().split(",");
		request.setAttribute("labe1",labels[0]);
		try {
			if(null!=labels[1] && !"".equals(labels[1])){
				request.setAttribute("labe2",labels[1]);
			}else{
				request.setAttribute("labe2","");
			}
		} catch (Exception e) {
			request.setAttribute("labe2","");
		}
		try {
			if(null!=labels[2] && !"".equals(labels[2])){
				request.setAttribute("labe3",labels[2]);
			}else{
				request.setAttribute("labe3","");
			}
		} catch (Exception e) {
			request.setAttribute("labe3","");
		}
		
		request.getRequestDispatcher("business/updatePeixun.jsp").forward(request, resp);
	}
	
	/**
	 * 修改培训/集训
	 * @param id
	 * @return
	 * @throws ParseException 
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("updateJixun")
	public void updateJixun(HttpServletRequest request,HttpServletResponse resp) throws ParseException, IOException, ServletException{
		String studyId=request.getParameter("studyId");
		Study study=studyService.getStudyDesc(studyId);
		study.setStudyUrl(CommonConfig.getProperty("PIC_URL_FRONT")+study.getStudyUrl());
		study.setContentUrl(CommonConfig.getProperty("PIC_URL_FRONT")+study.getContentUrl());
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		study.setStartStudyStr(sdf.format(study.getStartStudy()));
		study.setEndStudyStr(sdf.format(study.getEndStudy()));
		request.setAttribute("study",study);
		String labels[]=study.getStudyLabel().split(",");
		request.setAttribute("labe1",labels[0]);
		try {
			if(null!=labels[1] && !"".equals(labels[1])){
				request.setAttribute("labe2",labels[1]);
			}else{
				request.setAttribute("labe2","");
			}
		} catch (Exception e) {
			request.setAttribute("labe2","");
		}
		try {
			if(null!=labels[2] && !"".equals(labels[2])){
				request.setAttribute("labe3",labels[2]);
			}else{
				request.setAttribute("labe3","");
			}
		} catch (Exception e) {
			request.setAttribute("labe3","");
		}
		
		request.getRequestDispatcher("business/updateJiixun.jsp").forward(request, resp);
	}
	
	@RequestMapping("gotoAddPeixun")
	public void gotoAddPeixun(HttpServletRequest request,HttpServletResponse resp) throws ParseException, IOException{
		
		String studyTitle=request.getParameter("studyTitle");
		String studyDirection=request.getParameter("studyDirection");
		String maxStudent=request.getParameter("maxStudent");
		String startStudy=request.getParameter("startStudy");
		String endStudy=request.getParameter("endStudy");
		String studyPrice=request.getParameter("studyPrice");
		String studyLabel1=request.getParameter("studyLabel1");
		String studyLabel=studyLabel1;
		String studyLabel2=request.getParameter("studyLabel2");
		String studyLabel3=request.getParameter("studyLabel3");
		String studyContent=request.getParameter("studyContent");
		String studyCity=request.getParameter("studyCity");
	   //转型为MultipartHttpRequest(重点的所在)
       MultipartHttpServletRequest multipartRequest=null;
      
       try {
            multipartRequest  =  (MultipartHttpServletRequest) request; 
       } catch (Exception e) {
		   logger.error("咨询师头像为空");
		   resp.sendRedirect("business/addPeixun.jsp");
		   return ;
       }
       
//       String saveRootPath=request.getRealPath("/");//图片保存的根目录
		
	//  获得第1张图片
       MultipartFile personHead  =  multipartRequest.getFile("studyUrl"); 
       MultipartFile personHead2  =  multipartRequest.getFile("studyUrl2"); 
       MultipartFile personHead3  =  multipartRequest.getFile("studyUrl3"); 
       
       String picName=new Date().getTime()+"";
       String picName2=new Date().getTime()+"1";
       String picName3=new Date().getTime()+"2";
       
       String studyUrl=addImage(personHead, PIC_ADRESS,picName);
       
       String studyUrl2="";
       if(null!=personHead2){
    	   studyUrl2=addImage(personHead2, PIC_ADRESS,picName2);
       }
       String studyUrl3="";
       if(null!=personHead3){
    	   studyUrl3=addImage(personHead3, PIC_ADRESS,picName3);
       }
       
		String studyUrls[]=studyUrl.split("[.]");
		studyUrl=picName+"."+studyUrls[studyUrls.length-1];
		
		if(!studyUrl2.equals("")){
			String studyUrls2[]=studyUrl2.split("[.]");
			studyUrl2=picName2+"."+studyUrls2[studyUrls2.length-1];
		}
		if(!studyUrl3.equals("")){
			String studyUrls3[]=studyUrl3.split("[.]");
			studyUrl3=picName3+"."+studyUrls3[studyUrls3.length-1];
		}
		
		if(!studyLabel2.equals("")){
			studyLabel+=","+studyLabel2;
		}
		if(!studyLabel3.equals("")){
			studyLabel+=","+studyLabel3;
		}
		
		String counseTel=(String)request.getSession().getAttribute("counseTel");
		studyService.addPeixun(studyCity,counseTel,studyTitle,studyDirection,maxStudent,startStudy,endStudy,studyPrice,studyLabel,studyContent,studyUrl,studyUrl2,studyUrl3,"2","");
		resp.sendRedirect("business/mypeixun.jsp");
	}
	
	@RequestMapping("gotoAddJixun")
	public void gotoAddJixun(HttpServletRequest request,HttpServletResponse resp) throws ParseException, IOException{
		
		String studyTitle=request.getParameter("studyTitle");
		String studyDirection=request.getParameter("studyDirection");
		String maxStudent=request.getParameter("maxStudent");
		String startStudy=request.getParameter("startStudy");
		String endStudy=request.getParameter("endStudy");
		String studyPrice=request.getParameter("studyPrice");
		String studyLabel1=request.getParameter("studyLabel1");
		String studyLabel=studyLabel1;
		String studyLabel2=request.getParameter("studyLabel2");
		String studyLabel3=request.getParameter("studyLabel3");
		String studyContent=request.getParameter("studyContent");
		String studyCity=request.getParameter("studyCity");
		
	   //转型为MultipartHttpRequest(重点的所在)
       MultipartHttpServletRequest multipartRequest=null;
      
       try {
            multipartRequest  =  (MultipartHttpServletRequest) request; 
       } catch (Exception e) {
		   logger.error("咨询师头像为空");
		   resp.sendRedirect("business/addPeixun.jsp");
		   return ;
       }
       
//       String saveRootPath=request.getRealPath("/");//图片保存的根目录
		
   //  获得第1张图片
       MultipartFile personHead  =  multipartRequest.getFile("studyUrl"); 
       MultipartFile personHead2  =  multipartRequest.getFile("studyUrl2"); 
       MultipartFile personHead3  =  multipartRequest.getFile("studyUrl3"); 
       
       String picName=new Date().getTime()+"";
       String picName2=new Date().getTime()+"1";
       String picName3=new Date().getTime()+"2";
       
       String studyUrl=addImage(personHead, PIC_ADRESS,picName);
       
       String studyUrl2="";
       if(null!=personHead2){
    	   studyUrl2=addImage(personHead2, PIC_ADRESS,picName2);
       }
       String studyUrl3="";
       if(null!=personHead3){
    	   studyUrl3=addImage(personHead3, PIC_ADRESS,picName3);
       }
       
		String studyUrls[]=studyUrl.split("[.]");
		studyUrl=picName+"."+studyUrls[studyUrls.length-1];
		
		if(!studyUrl2.equals("")){
			String studyUrls2[]=studyUrl2.split("[.]");
			studyUrl2=picName2+"."+studyUrls2[studyUrls2.length-1];
		}
		if(!studyUrl3.equals("")){
			String studyUrls3[]=studyUrl3.split("[.]");
			studyUrl3=picName3+"."+studyUrls3[studyUrls3.length-1];
		}
		
		if(!studyLabel2.equals("")){
			studyLabel+=","+studyLabel2;
		}
		if(!studyLabel3.equals("")){
			studyLabel+=","+studyLabel3;
		}
		
		String counseTel=(String)request.getSession().getAttribute("counseTel");
		studyService.addPeixun(studyCity,counseTel,studyTitle,studyDirection,maxStudent,startStudy,endStudy,studyPrice,studyLabel,studyContent,studyUrl,studyUrl2,studyUrl3,"1","");
		resp.sendRedirect("business/25.jsp");
	}
	
	
	@RequestMapping("gotoUpdatePeixun")
	public void gotoUpdatePeixun(HttpServletRequest request,HttpServletResponse resp) throws ParseException, IOException{
		
		String studyTitle=request.getParameter("studyTitle");
		String studyId=request.getParameter("studyId");
		String studyDirection=request.getParameter("studyDirection");
		String maxStudent=request.getParameter("maxStudent");
		String startStudy=request.getParameter("startStudy");
		String endStudy=request.getParameter("endStudy");
		String studyPrice=request.getParameter("studyPrice");
		String studyLabel1=request.getParameter("studyLabel1");
		String studyLabel=studyLabel1;
		String studyLabel2=request.getParameter("studyLabel2");
		
		String studyLabel3=request.getParameter("studyLabel3");
		String studyContent=request.getParameter("studyContent");
		
	   //转型为MultipartHttpRequest(重点的所在)
       MultipartHttpServletRequest multipartRequest=null;
       String studyUrl="null";
       try {
            multipartRequest  =  (MultipartHttpServletRequest) request; 
       } catch (Exception e) {
		  e.printStackTrace();
       }
       
//       String saveRootPath=request.getRealPath("/");//图片保存的根目录
		
	//  获得第1张图片
       MultipartFile personHead  =  multipartRequest.getFile("studyUrl"); 
       System.out.println("personHead.getOriginalFilename()="+personHead.getOriginalFilename());
       if("".endsWith(personHead.getOriginalFilename())){
    	   studyUrl="";
    	   System.out.println("[培训修改studyUrl="+studyUrl+"]");
       }
       if(!"".equals(studyUrl)){
       String picName=new Date().getTime()+"";
       System.out.println("picName="+picName);
       studyUrl=addImage(personHead, PIC_ADRESS,picName);
		if(null==studyUrl || studyUrl.equals("")){
			studyUrl="";
		}
		String studyUrls[]=studyUrl.split("[.]");
		studyUrl=picName+"."+studyUrls[studyUrls.length-1];
       }
       if(!studyLabel2.equals("")){
			studyLabel+=","+studyLabel2;
		}
		if(!studyLabel3.equals("")){
			studyLabel+=","+studyLabel3;
		}
		String counseTel=(String)request.getSession().getAttribute("counseTel");
		studyService.addPeixun(studyId,counseTel,studyTitle,studyDirection,maxStudent,startStudy,endStudy,studyPrice,studyLabel,studyContent,studyUrl);
		resp.sendRedirect("business/mypeixun.jsp");
	}
	

	
	/**
	    * @Title: addImage
	    * @Description: 上传图片
	    * @param @param imgFile1
	    * @param @param saveRootPath
	    * @param @param telNumber
	    * @param @return    设定文件
	    * @return String    返回类型
	    * @date 2014-10-27 下午7:14:45
	    * @throws
	    * @author 赵应光
	     */
	    public String addImage(MultipartFile imgFile1,String saveRootPath,String telNumber) { 
	         String path1="personHead";
	         String path2=telNumber;
	       
	         //定义一个数组，用于保存可上传的文件类型 
	         List<String> fileTypes = new ArrayList<String>(); 
	         fileTypes.add("jpg"); 
	         fileTypes.add("jpeg"); 
	         fileTypes.add("bmp"); 
	         fileTypes.add("gif"); 
	         fileTypes.add("png"); 
	          
	         //保存第一张图片 
	         if(!(imgFile1.getOriginalFilename() ==null || "".equals(imgFile1.getOriginalFilename()))) { 
	             File file1 = this.getFile(imgFile1,path1,path2, fileTypes,saveRootPath);
	             return file1.getPath();
	         } 
	          return "";
	        
	    }  
	    
	    /**
	     *
	     * @Description: 保存文件并获取文件完整名
	     * @param @param imgFile
	     * @param @param typeName
	     * @param @param brandName
	     * @param @param fileTypes
	     * @param @param saveRootPath
	     * @param @return  
	     * @return File 
	     * @throws
	     * @author 赵应光
	     * @date 2014-10-27
	     */
	    private File getFile(MultipartFile imgFile,String typeName,String brandName,List<String> fileTypes,String saveRootPath) { 
	        String fileName = imgFile.getOriginalFilename(); 
	        logger.info("fileName="+fileName);
	        //获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名 
	         String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length()); 
	        
	         //对扩展名进行小写转换 
	         ext = ext.toLowerCase(); 
	          
	         File file = null; 
	        
	         if(fileTypes.contains(ext)) {                      //如果扩展名属于允许上传的类型，则创建文件 
	             file = this.creatFolder(typeName, "", brandName+"."+ext,saveRootPath); 
	          
	             try { 
	                imgFile.transferTo(file);                   //保存上传的文件 
	            } catch (IllegalStateException e) { 
	                e.printStackTrace(); 
	            } catch (IOException e) { 
	                e.printStackTrace(); 
	            } 
	         } 
	         return file; 
	    }  
	    
	    /**
	     * @Description: 保存文件到指定路径
	     * @param @param typeName
	     * @param @param brandName
	     * @param @param fileName
	     * @param @param saveRootPath
	     * @param @return  
	     * @return File 
	     * @throws
	     * @author 赵应光
	     * @date 2014-10-27
	     */
	    private File creatFolder(String typeName,String brandName,String fileName,String saveRootPath) { 
	         File file = null; 	         
	         typeName = typeName.replaceAll("/", "");               //去掉"/" 
	         typeName = typeName.replaceAll(" ", "");               //替换半角空格 
	         typeName = typeName.replaceAll(" ", "");               //替换全角空格 
	          
	         brandName = brandName.replaceAll("/", "");             //去掉"/" 
	         brandName = brandName.replaceAll(" ", "");             //替换半角空格 
	         brandName = brandName.replaceAll(" ", "");             //替换全角空格 
	         
	         File firstFolder = new File(saveRootPath + typeName);         //一级文件夹 
	        
	         if(firstFolder.exists()) {                             //如果一级文件夹存在，则检测二级文件夹 
	             File secondFolder = new File(firstFolder,brandName); 
	             if(secondFolder.exists()) {                        //如果二级文件夹也存在，则创建文件 
	                 file = new File(secondFolder,fileName); 
	             }else {                                            //如果二级文件夹不存在，则创建二级文件夹 
	                 secondFolder.mkdir(); 
	                 file = new File(secondFolder,fileName);        //创建完二级文件夹后，再合建文件 
	             } 
	         }else {                                                //如果一级不存在，则创建一级文件夹 
	             firstFolder.mkdir(); 
	             File secondFolder = new File(firstFolder,brandName); 
	             if(secondFolder.exists()) {                        //如果二级文件夹也存在，则创建文件 
	                 file = new File(secondFolder,fileName); 
	             }else {                                            //如果二级文件夹不存在，则创建二级文件夹 
	                 secondFolder.mkdir(); 
	                 file = new File(secondFolder,fileName); 
	             } 
	         } 
	         return file; 
	    }
}
